package cn.com.ccxe.core.util;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import cn.com.ccxe.core.entity.Keyword;

public class KeywordSet extends HashSet<Keyword> {

	private static final long serialVersionUID = 1L;
	
	/**
	 * 根据字符生成{@link Keyword}对象，但仅仅设置其<code>type</code>属性
	 * @param keyword
	 * @return
	 */
	public KeywordSet convert(String [] keywords){ 
		
		for (String str : keywords) {
			Keyword keyword = new Keyword();
			keyword.setText(str);
			boolean isSuccess = add(keyword);
			if(!isSuccess) {
				throw new RuntimeException("将type："+str+"构建对象失败！");
			}
		}
		return this;
	}
	
	/**
	 * 装换成正则表达式语句
	 * @return
	 */
	public String toRule() {
		StringBuffer filter = new StringBuffer(".*(");
		int count = 0;
		for (Iterator<Keyword> iter = this.iterator(); iter.hasNext();) {
			Keyword keyword = iter.next();
			if(count == 0) {
				filter.append(keyword.getText());
			}else {
				filter.append("|"+keyword.getText());
			}
			count++;
		}
		filter.append(").*");
		return filter.toString();
	}
	
	public void add(List<Keyword> keywords) {
		if(keywords == null || keywords.size() <= 0) {
			return;
		}
		for (Iterator<Keyword> iter = keywords.iterator(); iter.hasNext();) {
			Keyword keyword = iter.next();
			if(keyword != null && keyword.getText().length()>0) {
				add(keyword);
			}
		}
	}
	
}
